//
//  RunViewController.m
//  Shine
//
//  Created by 王斌 on 16/3/9.
//  Copyright © 2016年 王斌. All rights reserved.
//

#import "RunViewController.h"
#import "LXCircleAnimationView.h"
#import "PNChart.h"
#import "JBUnitView.h"
#import "JBSXRCUnitTileView.h"
#import "WBin_BaiduMapViewController.h"

@interface RunViewController ()<JBUnitGridViewDelegate, JBUnitViewDelegate, JBUnitViewDataSource>
@property (nonatomic, retain) JBUnitView *unitView;
@property (nonatomic, retain) UITableView *tableView;

/// 环形进度
@property (nonatomic, strong) LXCircleAnimationView *circleProgressView;

/// 步数Label
@property(nonatomic, strong) UILabel *countLabel;

/// 大卡
@property(nonatomic, strong) UILabel *calorieLabel;

/// 活跃时间
@property(nonatomic, strong) UILabel *activeTimeLabel;

/// 公里数
@property(nonatomic, strong) UILabel *distanceLabel;

@property(nonatomic, strong) UIView *dateView;

@property(nonatomic, strong) UIView *tapView;

@property (strong, nonatomic) IBOutlet UIView *lineView;


@end

@implementation RunViewController

+ (instancetype)shareRunViewController{
    static RunViewController *runVC = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        runVC = [[RunViewController alloc] init];
    });
    return runVC;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.userInteractionEnabled = YES;

    
    /// 创建视图
    [self createView];
    
    /// 创建日历视图
    [self createDate];
    
    [self clockMasonry];
    
}

/// 给clock添加约束
- (void)clockMasonry{
    
    UILabel *clock6 = [[UILabel alloc] init];
    clock6.font = [UIFont systemFontOfSize:11];
    clock6.textAlignment = NSTextAlignmentCenter;
    clock6.textColor = [UIColor lightTextColor];
    clock6.text = @"6:00";
    [self.view addSubview:clock6];
    
    UILabel *clock12 = [[UILabel alloc] init];
    clock12.font = [UIFont systemFontOfSize:11];
    clock12.textAlignment = NSTextAlignmentCenter;
    clock12.textColor = [UIColor lightTextColor];
    clock12.text = @"12:00";
    [self.view addSubview:clock12];
    
    UILabel *clock18 = [[UILabel alloc] init];
    clock18.font = [UIFont systemFontOfSize:11];
    clock18.textAlignment = NSTextAlignmentCenter;
    clock18.textColor = [UIColor lightTextColor];
    clock18.text = @"18:00";
    [self.view addSubview:clock18];
    
    UILabel *clock0 = [[UILabel alloc] init];
    clock0.font = [UIFont systemFontOfSize:11];
    clock0.textAlignment = NSTextAlignmentCenter;
    clock0.textColor = [UIColor lightTextColor];
    clock0.text = @"0:00";
    [self.view addSubview:clock0];
    
     __weak typeof (self.view)weakSelf = self.view;
    [clock6 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(weakSelf.mas_left).with.offset((WIDTH_SCREEN - 40) / 4);
        make.bottom.equalTo(weakSelf.mas_bottom).with.offset(-10);
        make.size.mas_equalTo(CGSizeMake(30, 20));
    }];
    [clock12 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(weakSelf.mas_left).with.offset((WIDTH_SCREEN - 40) / 4 * 2);
        make.bottom.equalTo(weakSelf.mas_bottom).with.offset(-10);
        make.size.mas_equalTo(CGSizeMake(30, 20));
    }];
    [clock18 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(weakSelf.mas_left).with.offset((WIDTH_SCREEN - 40) / 4 * 3);
        make.bottom.equalTo(weakSelf.mas_bottom).with.offset(-10);
        make.size.mas_equalTo(CGSizeMake(30, 20));
    }];
    [clock0 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(weakSelf.mas_left).with.offset(WIDTH_SCREEN - 40);
        make.bottom.equalTo(weakSelf.mas_bottom).with.offset(-10);
        make.size.mas_equalTo(CGSizeMake(30, 20));
    }];
    
    // 创建slider
    for (NSInteger i = 1; i < 13; i++){
        UIView *slider = [[UIView alloc] initWithFrame:CGRectMake((WIDTH_SCREEN - 40) / 12 * i, 0, 2, 0)];
        slider.backgroundColor = COLORWHITE;
        slider.tag = 799 + i;
        [self.lineView addSubview:slider];
        [slider bringSubviewToFront:self.lineView];
    }
    
}

#pragma mark 查找步数
- (void)searchCount{
    
    /// 获取当前时区时间
    NSDate *localDate = [NSDate dateWithTimeIntervalSinceNow:[[NSTimeZone systemTimeZone] secondsFromGMTForDate:[NSDate date]]];
    
    ///NSDate转化成NSString
    NSString *strDate = [NSString stringWithFormat:@"%@",localDate];
    
    /// 截取年 月 日 小时
    NSString *tempYear = [strDate substringToIndex:4];
    NSString *tempMonth = [strDate substringWithRange:(NSMakeRange(5, 2))];
    NSString *tempDay = [strDate substringWithRange:(NSMakeRange(8, 2))];
    NSString *tempHour = [strDate substringWithRange:(NSMakeRange(11, 2))];
    NSNumber *year = [NSNumber numberWithInt:[tempYear intValue]];
    NSNumber *month = [NSNumber numberWithInt:[tempMonth intValue]];
    NSNumber *day = [NSNumber numberWithInt:[tempDay intValue]];
    NSNumber *hour = [NSNumber numberWithInt:[tempHour intValue]];
    
    [self theAssignmentYear:year month:month day:day hour:hour];
}

- (void)theAssignmentYear:(NSNumber *)year month:(NSNumber *)month day:(NSNumber *)day hour:(NSNumber *)hour{

    [self.dateButton setTitle:[NSString stringWithFormat:@"%@-%@-%@", year, month, day] forState:UIControlStateNormal];
    /// 根据上面截取的从数据库获取步数信息
    NSArray *healthArr = [[CoreDataManager shareInstance] selectAll:year month:month day:day hour:nil];
    NSInteger count = 0;
    for (HealthKit *temp in healthArr) {
        NSInteger i = [temp.count integerValue];
        count += i;
    }
    
    NSMutableArray *sliderArr = [NSMutableArray array];
    // 给小时进度条赋值
    for (NSInteger i = 0; i < 24; i++) {
        NSArray *tempArr = [[CoreDataManager shareInstance] selectAll:year month:month day:day hour:[NSNumber numberWithInteger:i]];
        if (tempArr.count) {
            [sliderArr addObject:[tempArr firstObject]];
        }
    }
    
    
    dispatch_async(dispatch_get_main_queue(), ^{
        
        for (NSInteger i = 1; i < 13; i++) {
            UIView *sliderView = [self.view viewWithTag:799 + i];
            sliderView.frame = CGRectMake((WIDTH_SCREEN - 40) / 12 * i, 0, 2, 0);
        }
        
        /// 柱状图
        for (HealthKit *tempKit in sliderArr) {
            UIView *sliderView = [self.view viewWithTag:799 + [tempKit.hour intValue] / 2];
            sliderView.frame = CGRectMake((WIDTH_SCREEN - 40) / 12 * [tempKit.hour intValue] / 2, -[tempKit.count intValue] / 33.34, 2, [tempKit.count intValue] / 33.34);
            
        }
        

        /// 进度条
        self.circleProgressView.percent = count / 100;
        
        // 时间
        CGFloat active = count / 104;
        NSInteger h = 0;
        if (active > 59) {
            h = active / 60;
            active = active - 60 * h;
        }
        
        /// 时间
        self.activeTimeLabel.text = [NSString stringWithFormat:@"%ldh %.fm", (long)h, active];
        
        // 公里
        self.distanceLabel.text = [NSString stringWithFormat:@"%.1f", count / 1464.1];
        
        /// 步数
        self.countLabel.text = [NSString stringWithFormat:@"%ld", (long)count];
        
        // 大卡赋值
        self.calorieLabel.text = [NSString stringWithFormat:@"%.f",count / 38.0];
        
        if (!count) {
            self.calorieLabel.text = @"0";
            self.activeTimeLabel.text = @"0";
            self.distanceLabel.text = @"0";
        }
    });

    
    
    
    
    
//    for (NSInteger i = 0; i < sliderArr.count; i++) {
//        HealthKit *temp = sliderArr[i];
//        UIView *sliderView = [self.view viewWithTag:799 + [temp.hour intValue]];
//        [UIView animateWithDuration:1 animations:^{
//            sliderView.frame =  CGRectMake(sliderView.frame.origin.x, sliderView.frame.origin.y, 2, [temp.count intValue] / 16.67);
//        }];
//    }
}

#pragma mark 创建视图
- (void)createView{
    self.dateButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.dateButton.frame = CGRectMake(WIDTH_SCREEN / 2 - 80, 0, 160, 40);
//    self.dateButton.backgroundColor = [UIColor redColor];
    [self.dateButton addTarget:self action:@selector(dateButton:) forControlEvents:UIControlEventTouchUpInside];
    [self.navigationController.navigationBar addSubview:self.dateButton];
    
    self.circleProgressView = [[LXCircleAnimationView alloc] initWithFrame:CGRectMake(WIDTH_SCREEN / 10.35, HEIGHT_SCREEN / 4, WIDTH_SCREEN - WIDTH_SCREEN / 10.35 * 2, WIDTH_SCREEN - WIDTH_SCREEN / 10.35 * 2)];
    self.circleProgressView.bgImage = [UIImage imageNamed:@"backgroundImage"];
    self.circleProgressView.percent = 0.f;
    [self.view addSubview:self.circleProgressView];
    
    __weak typeof (self.view)weakSelf = self.view;
    __weak typeof (self.circleProgressView)weakCircleView = self.circleProgressView;


    UIButton *mapButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [mapButton setImage:[UIImage imageNamed:@"iconfont-ditu"] forState:UIControlStateNormal];
    [self.view addSubview:mapButton];
    [mapButton addTarget:self action:@selector(tapMap) forControlEvents:UIControlEventTouchUpInside];
    [mapButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(weakSelf.mas_right);
        make.top.equalTo(weakCircleView.mas_bottom).with.offset(-100);
        make.size.mas_equalTo(CGSizeMake(40, 35));
    }];
    
    /// 创建今日步数
    UILabel *todayLabel = [[UILabel alloc] init];
    todayLabel.text = @"今日步数";
    todayLabel.textAlignment = NSTextAlignmentCenter;
    todayLabel.font = [UIFont systemFontOfSize:WIDTH_SCREEN / 18 weight:1];
    todayLabel.textColor = COLORWHITE;
    [self.circleProgressView addSubview:todayLabel];
    
    /// 创建当前步数label
    self.countLabel = [[UILabel alloc] init];
    self.countLabel.textColor = COLORYELLO;
    self.countLabel.textAlignment = NSTextAlignmentCenter;
//    self.countLabel.font = [UIFont systemFontOfSize:60 weight:1];
    self.countLabel.font = [UIFont fontWithName:@"DBLCDTempBlack" size:WIDTH_SCREEN / 5.9];
    [self.circleProgressView addSubview:self.countLabel];
    __weak typeof (self.countLabel)weakCountLabel = self.countLabel;
    ///防止循环引用
    
    [self.countLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(weakCircleView.mas_centerX);
        make.centerY.equalTo(weakCircleView.mas_centerY).with.offset(-20);
        make.size.mas_equalTo(CGSizeMake(WIDTH_SCREEN / 2, WIDTH_SCREEN / 5.5));
    }];
    
    [todayLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(weakCountLabel.mas_top).with.offset(-10);
        make.centerX.equalTo(weakCountLabel.mas_centerX).with.offset(0);
        make.size.mas_equalTo(CGSizeMake(100, 50));
    }];
    
    
    /// 创建目标label
    UILabel *targetLabel = [[UILabel alloc] init];
    targetLabel.textColor = [UIColor lightTextColor];
    targetLabel.text = @"目标:10000";
    targetLabel.font = [UIFont systemFontOfSize:15];
    targetLabel.textAlignment = NSTextAlignmentCenter;
    [self.circleProgressView addSubview:targetLabel];
    [targetLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(weakCountLabel.mas_centerX).with.offset(0);
        make.top.equalTo(weakCountLabel.mas_bottom).with.offset(0);
        make.size.mas_equalTo(CGSizeMake(100, 50));
    }];

    /// 创建大卡TitleLabel
    UILabel *calorieTitleLabel = [[UILabel alloc] init];
    calorieTitleLabel.text = @"大卡";
    calorieTitleLabel.textAlignment = NSTextAlignmentCenter;
    calorieTitleLabel.textColor = COLORWHITE;
    calorieTitleLabel.font = [UIFont systemFontOfSize:20];
    [self.view addSubview:calorieTitleLabel];
    
    /// 创建大卡Label
    self.calorieLabel = [[UILabel alloc] init];
    self.calorieLabel.textAlignment = NSTextAlignmentCenter;
    self.calorieLabel.font = [UIFont systemFontOfSize:30];
    self.calorieLabel.textColor = COLORYELLO;
    [self.view addSubview:self.calorieLabel];
    
    /// 创建活跃时间TitleLabel
    UILabel *activeTimeTitleLabel = [[UILabel alloc] init];
    activeTimeTitleLabel.text = @"活跃时间";
    activeTimeTitleLabel.textAlignment = NSTextAlignmentCenter;
    activeTimeTitleLabel.textColor = COLORWHITE;
    activeTimeTitleLabel.font = [UIFont systemFontOfSize:20];
    [self.view addSubview:activeTimeTitleLabel];

    /// 创建活跃时间label
    self.activeTimeLabel = [[UILabel alloc] init];
    self.activeTimeLabel.textAlignment = NSTextAlignmentCenter;
    self.activeTimeLabel.textColor = COLORYELLO;
    self.activeTimeLabel.font = [UIFont systemFontOfSize:30];
    [self.view addSubview:self.activeTimeLabel];
    
    /// 创建公里TitleLabel
    UILabel *distanceTitleLabel = [[UILabel alloc] init];
    distanceTitleLabel.textAlignment = NSTextAlignmentCenter;
    distanceTitleLabel.text = @"公里";
    distanceTitleLabel.textColor = COLORWHITE;
    distanceTitleLabel.font = [UIFont systemFontOfSize:20];
    [self.view addSubview:distanceTitleLabel];
    
    /// 创建公里label
    self.distanceLabel = [[UILabel alloc] init];
    self.distanceLabel.textAlignment = NSTextAlignmentCenter;
    self.distanceLabel.textColor = COLORYELLO;
    self.distanceLabel.font = [UIFont systemFontOfSize:30];
    [self.view addSubview:self.distanceLabel];
    
    /// 为6个控件添加约束
    [activeTimeTitleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(weakSelf.mas_centerX).with.offset(0);
        make.top.equalTo(weakSelf.mas_top).with.offset(50);
        make.size.mas_equalTo(CGSizeMake(80, 25));
    }];
    
    [self.activeTimeLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(weakCircleView.mas_centerX);
        make.top.equalTo(activeTimeTitleLabel.mas_bottom).with.offset(5);
        make.size.mas_equalTo(CGSizeMake(WIDTH_SCREEN / 3, 50));
    }];

    [calorieTitleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(activeTimeTitleLabel.mas_top);
        make.left.mas_equalTo(WIDTH_SCREEN / 8.28);
        make.size.mas_equalTo(CGSizeMake(40, 25));
    }];

    [self.calorieLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(calorieTitleLabel.mas_centerX);
        make.top.equalTo(calorieTitleLabel.mas_bottom).with.offset(5);
        make.size.mas_equalTo(CGSizeMake(80, 50));
    }];
    
    [distanceTitleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(activeTimeTitleLabel.mas_top);
        make.left.mas_equalTo(WIDTH_SCREEN - WIDTH_SCREEN / 8.28 - 40);
        make.size.mas_equalTo(CGSizeMake(40, 25));
    }];
    
    [self.distanceLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(distanceTitleLabel.mas_centerX);
        make.top.equalTo(activeTimeTitleLabel.mas_bottom).with.offset(5);
        make.size.mas_equalTo(CGSizeMake(80, 50));
    }];
    
}

#pragma mark 地图
- (void)tapMap{
    WBin_BaiduMapViewController *mapVC = [[WBin_BaiduMapViewController alloc] init];
    [self presentViewController:mapVC animated:YES completion:^{
        
    }];
    
}

#pragma mark 日历button点击方法
- (void)dateButton:(UIButton *)button{
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.4 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        self.unitView.hidden = NO;
    });

    [UIView animateWithDuration:0.5 animations:^{
        self.unitView.alpha = 1;
        self.tapView.frame = CGRectMake(0, HEIGHT_SCREEN / 2, WIDTH_SCREEN, HEIGHT_SCREEN / 2);
        self.dateView.frame = CGRectMake(0, 0, WIDTH_SCREEN, HEIGHT_SCREEN );
    }];
    
}

- (void)createDate{
    
    self.dateView = [[UIView alloc] initWithFrame:CGRectMake(0, -49, WIDTH_SCREEN, 0)];
    self.dateView.backgroundColor = COLORBLACK;
    self.dateView.alpha = 0.9;
    [self.view addSubview:self.dateView];
    
    self.tapView = [[UIView alloc] initWithFrame:CGRectMake(0, HEIGHT_SCREEN / 2, WIDTH_SCREEN, 0)];
    self.tapView.backgroundColor =[UIColor clearColor];
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hiddenDateView)];
    [self.tapView addGestureRecognizer:tap];
    [self.dateView addSubview:self.tapView];
    
    self.unitView = [[JBUnitView alloc] initWithFrame:CGRectMake(0, 0, WIDTH_SCREEN, HEIGHT_SCREEN / 2) UnitType:UnitTypeMonth SelectedDate:[NSDate date] AlignmentRule:JBAlignmentRuleTop Delegate:self DataSource:self];
    self.unitView.hidden = YES;
    [self.dateView addSubview:self.unitView];

}

- (void)hiddenDateView{
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.4 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        self.unitView.hidden = YES;
    });
    [UIView animateWithDuration:0.5 animations:^{
        self.unitView.alpha = 0;
        self.dateView.frame = CGRectMake(0, 0, WIDTH_SCREEN, 0);
        self.tapView.frame = CGRectMake(0, HEIGHT_SCREEN / 2, WIDTH_SCREEN, 0);
    }];
    
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self searchCount];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



#pragma mark 日历的方法

#pragma mark 日历的点击方法
/**************************************************************
 *@Description:选择某一天
 *@Params:
 *  unitView:当前unitView
 *  date:选择的日期
 *@Return:nil
 **************************************************************/
- (void)unitView:(JBUnitView *)unitView SelectedDate:(NSDate *)date
{
//    ///首先[NSTimeZone systemTimeZone]是为了获取当前所在时区
//    NSTimeZone *zone = [NSTimeZone systemTimeZone];
//    ///secondsFromGMTForDate是为了获取与当前时区相差的秒数
//    NSInteger seconds = [zone secondsFromGMTForDate:date];
//    ///输出当前所在时区的时间
//     NSDate *localDate  = [NSDate dateWithTimeInterval:seconds sinceDate:date];
//    
//    [self theAssignmentDate:localDate];
//    [self hiddenDateView];
}

#pragma mark - JBUnitViewDelegate
/**************************************************************
 *@Description:获取当前UnitView中UnitTileView的高度
 *@Params:
 *  unitView:当前unitView
 *@Return:当前UnitView中UnitTileView的高度
 **************************************************************/
- (CGFloat)heightOfUnitTileViewsInUnitView:(JBUnitView *)unitView
{
    return WIDTH_SCREEN / 7;
}

/**************************************************************
 *@Description:获取当前UnitView中UnitTileView的宽度
 *@Params:
 *  unitView:当前unitView
 *@Return:当前UnitView中UnitTileView的宽度
 **************************************************************/
- (CGFloat)widthOfUnitTileViewsInUnitView:(JBUnitView *)unitView
{
    return WIDTH_SCREEN / 7;
}


/**************************************************************
 *@Description:更新unitView的frame
 *@Params:
 *  unitView:当前unitView
 *  newFrame:新的frame
 *@Return:nil
 **************************************************************/
- (void)unitView:(JBUnitView *)unitView UpdatingFrameTo:(CGRect)newFrame
{
    self.tableView.frame = CGRectMake(0.0f, newFrame.size.height, self.view.bounds.size.width, self.view.bounds.size.height - newFrame.size.height);
}

/**************************************************************
 *@Description:重新设置unitView的frame
 *@Params:
 *  unitView:当前unitView
 *  newFrame:新的frame
 *@Return:nil
 **************************************************************/
- (void)unitView:(JBUnitView *)unitView UpdatedFrameTo:(CGRect)newFrame
{
    //NSLog(@"OK");
}

#pragma mark -
#pragma mark - JBUnitViewDataSource
/**************************************************************
 *@Description:获得unitTileView
 *@Params:
 *  unitView:当前unitView
 *@Return:unitTileView
 **************************************************************/
- (JBUnitTileView *)unitTileViewInUnitView:(JBUnitView *)unitView
{
    return [[JBSXRCUnitTileView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, WIDTH_SCREEN / 6, HEIGHT_SCREEN / 2 / 7)];
}


#pragma mark 设备不支持健康
- (void)isHealthDataAvailableNot{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"警告" message:@"设备与软件不兼容, 感谢您对本软件的支持" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *alert = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    [alertController addAction:alert];
    [self presentViewController:alertController animated:YES completion:^{
        
    }];

}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
